﻿using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static X23.Util.CacheUtil.CacheConst;

namespace X23.Util.CacheUtil
{
    /// <summary>
    /// X23Cache缓存启动设置
    /// </summary>
    public static class X23CacheSetup
    {
        /// <summary>
        /// 启动缓存
        /// </summary>
        /// <param name="services"></param>
        /// <param name="cacheType">缓存方式(1内存缓存 2Redis缓存)</param>
        /// <param name="redisConfiguration">Redis连接字符串(当cacheType==2时必填)</param>
        public static void AddX23CacheSetup(this IServiceCollection services, CacheSetupType cacheType = CacheSetupType.MemoryCache, string redisConfiguration = null)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            if (cacheType== CacheSetupType.MemoryCache)
            {
                services.AddScoped<ICacheService, MemoryCacheService>();
                services.AddMemoryCache();
            }
            else
            {
                if (string.IsNullOrEmpty(redisConfiguration))
                {
                    throw new Exception("请填写Redis连接字符串！");
                }
                //Redis用法  https://stackexchange.github.io/StackExchange.Redis/Basics
                services.AddScoped<ICacheService, RedisCacheService>();
                services.AddSingleton<ConnectionMultiplexer>(sp =>
                {
                    var configuration = ConfigurationOptions.Parse(redisConfiguration, true);
                    configuration.ResolveDns = true;
                    return ConnectionMultiplexer.Connect(configuration);
                });
            }
        }
    }
}
